package net.cmkj.mine.core.admin.service;

import com.jfinal.aop.Inject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.common.controller.BaseController;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.core.admin.calculate.CalculateService;
import net.cmkj.mine.util.StringUtil;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class OpenController extends BaseController {

    @Inject
    private MineService service;

    @Inject
    private CalculateService calculateService;

    public void form() throws Exception {
        String tablename = getPara("tablename");
        if(getPara("type")==null){
            setAttr("type", 0);
        }else{
            setAttr("type", 1);
        }
        Long id = getParaToLong("id");
        if (id != null) {
            setAttr("item", JsonKit.toJson(service.findById(tablename, id)));
        } else {
            setAttr("item", JsonKit.toJson(new Record()));
        }
        setAttr("tablename", tablename);
        setAttr("moduleid", getPara("moduleid"));
        render("serviceForm.html");
    }

    public void showColumns() throws Exception {
        long moduleid = getParaToLong("moduleid");
        renderJson(service.showColumns(moduleid));
    }

    public void getSelectData() throws Exception {
        long moduleid = getParaToLong("foreignTable");
        String foreignKey = getPara("foreignKey");
        renderJson(service.getSelectData(moduleid, foreignKey));
    }

    public void getCalList() throws Exception {
        Long moduleid = getParaToLong("moduleid");
        renderJson(calculateService.getList(moduleid));
    }

    public void uploadFile() throws Exception {
        String tablename = getPara("tablename");
        String path = PathKit.getWebRootPath()+"/upload/"+tablename;
        UploadFile file = getFile("file", "temp");
        File source = file.getFile();
        String fileName = file.getFileName();
        String uuid = StringUtil.getUUID()+fileName.substring(fileName.lastIndexOf("."));
        try {
            File targetDir = new File(path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File target = new File(targetDir, uuid);
            if (!target.exists()) {
                target.createNewFile();
            }
           /*
           FileOutputStream fos = new FileOutputStream(target);
            byte[] bts = new byte[1024];
            while (fis.read(bts, 0, 1024) != -1) {
                fos.write(bts, 0, 1024);
            }
            fos.close();
            fis.close();
            */
            FileChannel inputChannel = new FileInputStream(source).getChannel();
            FileChannel outputChannel = new FileOutputStream(target).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            inputChannel.close();
            outputChannel.close();
            source.delete();
        } catch (FileNotFoundException e) {
            renderJson(InvokeResult.failure("上传出现错误，请稍后再上传"));
            e.printStackTrace();
        } catch (IOException e) {
            renderJson(InvokeResult.failure("文件写入服务器出现错误，请稍后再上传"));
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", 1);
        result.put("message", "上传成功！");
        result.put("url", getRequest().getContextPath()+"/upload/"+tablename+"/"+uuid);
        result.put("name", file.getFileName());
        renderJson(result);
    }

    public void save() throws Exception {
        String tablename = getPara("tablename");
        Map<String, String[]> params = getParaMap();
        renderJson(service.save(tablename, params, new SysUser().setId(6)));
    }

    public void tableFileDownload() throws Exception {
        String name = getPara("name");
        String url = getPara("url");
        renderFile(new File(PathKit.getWebRootPath()+url), name);
    }

    public void calculate() throws Exception {
        renderJson(calculateService.calculate(getPara("formula"), getPara("mapstr")));
    }
}
